<template>
  <section>
    <transition enter-active-class="animate__animated animate__fadeIn" mode="out-in">
      <section>
        <!-- 查询表单 -->
<ZyTableQueryForm
  v-model:ruleForm="query.params"
  :rules="queryRule"
  @query="goPage(1)"
  @reset="goReset"
>


  <el-form-item style="margin-right: 200px;">
    <el-button type="primary" style="width: 68px; height: 24px;" @click="openAddDialog">新增</el-button>
  </el-form-item>
</ZyTableQueryForm>


        <!-- 新增弹窗 -->
        <el-dialog title="新增 RTSP 流" v-model="adddialogVisible" width="500px">
          <el-form :model="addform" ref="addFormRef" label-width="100px" :rules="addRules">
            <el-form-item label="RTSP 流地址" prop="rtspUrl">
              <el-input v-model="addform.rtspUrl" placeholder="请输入 RTSP 流地址" />
            </el-form-item>
            <el-form-item label="监控点 名称" prop="cameras_name">
              <el-input v-model="addform.cameras_name" placeholder="请输入 监控点 名称" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="adddialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitAddForm">提交</el-button>
          </template>
        </el-dialog>

        <!-- 数据表格 -->
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          @sort-change="handleSortChange"
          @selection-change="handleSelectionChange"
          row-key="app"
          :expand-row-keys="expandedRowKeys"
        >

          <el-table-column type="selection" align="center" />
          <!-- 序号列 -->
          <el-table-column type="index" label="序号" width="60" align="center"/>
          <el-table-column prop="url" label="拉流地址" align="center" header-align="center" width="250" show-overflow-tooltip />
          <el-table-column prop="key" label="键" align="center" width="100" show-overflow-tooltip />
          <el-table-column prop="bytesSpeed" label="传输速度" align="center" width="120" show-overflow-tooltip />
          <el-table-column prop="liveSecs" label="流运行时间" align="center" width="100" show-overflow-tooltip />
          <el-table-column prop="rePullCount" label="拉流失败后重新拉流的次数" align="center" width="120" show-overflow-tooltip />

          <!-- 源信息嵌套表格 -->
          <el-table-column prop="src" label="源信息" align="center" header-align="center" width="300">
            <template #default="{ row }">
              <el-table
                :data="[row.src || {}]"
                border
                size="small"
                style="width: 100%; font-size: 12px;"
                header-row-class-name="hidden-header"
              >
                <el-table-column label="应用名称" prop="app" align="center" header-align="center" />
                <el-table-column label="流名称" prop="stream" align="center" header-align="center" />
                <el-table-column label="虚拟主机名" prop="vhost" align="center" header-align="center" />
              </el-table>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="流状态" width="300" show-overflow-tooltip header-align="center" align="center">
            <template #default="{ row }">
              <el-button
                :type="row.status === 0 ? 'success' : 'danger'"
                size="small"
                round
                plain
              >
                {{ row.status === 0 ? '正常' : '异常' }}
              </el-button>
            </template>
          </el-table-column>

          <el-table-column prop="totalBytes" label="累计已传输的总字节数" align="center" header-align="center" width="250" show-overflow-tooltip />
          <el-table-column prop="totalReaderCount" label="观看者数量" align="center" header-align="center" width="300" show-overflow-tooltip />

          <el-table-column label="操作" align="center" header-align="center" width="150">
            <template #default="{ row }">
              <el-button type="danger" @click="openDelDialog(row.key)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <ZyElPagination
          v-model:currentPage="query.pagination.current"
          v-model:pageSize="query.pagination.pageSize"
          :total="tempData.total"
        />

        <!-- 删除确认弹窗 -->
        <el-dialog v-model="dialogVisible" title="确认删除" width="400px">
          <el-form :model="form" ref="delFormRef">
            <el-form-item label="Key">
              <el-input v-model="form.key" disabled />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="danger" @click="submitDelForm">确认删除</el-button>
          </template>
        </el-dialog>

      </section>
    </transition>
  </section>
</template>

<script>
import { reactive, ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import api from '@/api/axios.js'

export default {
  name: 'YourComponentName',

  data() {
    return {
      query: reactive({
        params: { app: '' },
        pagination: { current: 1, pageSize: 10 }
      }),
      queryRule: reactive({}),
      tempData: reactive({ total: 0 }),

      dialogVisible: false,
      form: reactive({ key: '' }),
      

      adddialogVisible: false,
      addform: reactive({ rtspUrl: '' ,cameras_name:''}),

      expandedRowKeys: ref([]),

      tableData: ref([]),
    }
  },

  methods: {
    openDelDialog(key) {
      this.form.key = key
      this.dialogVisible = true
    },

    async submitDelForm() {
      const formData = new URLSearchParams()
      formData.append('key', this.form.key)

      try {
        await api.post('/delStreamProxy', formData)
        ElMessage.success('删除成功')
        this.dialogVisible = false
        this.getData()
      } catch (err) {
        ElMessage.error('删除失败')
        console.error(err)
      }
    },

    openAddDialog() {
      this.addform.rtspUrl = ''
      this.adddialogVisible = true
    },

    submitAddForm() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        try {
          await api.post('/addStreamProxy', new URLSearchParams({ url: this.addform.rtspUrl, url_name :this.addform.cameras_name })).then(res=>{
                console.log(res)
                
                if(res.code!=400){
                    ElMessage.success('新增成功!')
                }else{
                    ElMessage.error(res.msg)
                }
          })
          this.adddialogVisible = false
          this.getData()
        } catch (err) {
          ElMessage.error('新增失败')
          console.error(err)
        }
      })
    },

  async getData() {
    try {
      const res = await api.post('/listStreamProxy')
      const data = res.data || []
      const { current, pageSize } = this.query.pagination
      const filtered = data.filter(item => !this.query.params.app || item.app?.includes(this.query.params.app))
      this.tempData.total = filtered.length
      this.tableData = filtered.slice((current - 1) * pageSize, current * pageSize)
      this.expandedRowKeys = []
    } catch (err) {
      console.error('获取数据失败', err)
      // 请求失败时清空数据
      this.tableData = []
      this.tempData.total = 0
      this.expandedRowKeys = []
    } finally {
    } 
  },


    goPage(page) {
      this.query.pagination.current = page
      this.getData()
    },

    goReset() {
      this.query.params.app = ''
      this.query.pagination.current = 1
      this.getData()
    },

    handleSortChange(e) {
      console.log('排序：', e)
    },

    handleSelectionChange(selection) {
      console.log('选中：', selection)
    }
  },

  mounted() {
    this.getData()
  }
}
</script>
